package com.jlastu.znb.view; // 替换为您的包名

import static android.util.TypedValue.COMPLEX_UNIT_SP;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jlastu.znb.R;
import com.jlastu.znb.constan.Constance;
import com.jlastu.znb.contract.NongyouContract;
import com.jlastu.znb.entity.ShopUserData;
import com.jlastu.znb.utils.SpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NongyouFragment extends Fragment implements NongyouContract.INongyouView {
    private ImageView mImageView;
    private TextView mTextView;
    private ImageView mPubNong;

    private SpUtils mSpUtils; // 如果您使用SpUtils，请初始化
    private ViewPager2 viewPager2;
    private TabLayout tabLayout;
    public TextView toMyTextView;
    public TextView toBeReceivedTextView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 加载布局
        return inflater.inflate(R.layout.fragment_nongyou, container, false);
    }

    private List<ShopUserData> dataFollowList;
    private List<ShopUserData> dataList = new ArrayList<>();
    private int mPage = 1;

    private void initDiscountList(int page) {
        Log.d("打印当前第几页", page + "");
        String imageUrl = "https://t7.baidu.com/it/u=4031278332,3112565627&fm=193&f=GIF";
        if (page == 1) {
            List<ShopUserData> lists = new ArrayList<>();
            ShopUserData shopUserData = new ShopUserData("节日快乐",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "商秋", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData.setUserId("0");
            lists.add(shopUserData);
            ShopUserData shopUserData1 = new ShopUserData("蝉鸣",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "北夏", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData1.setUserId("1");
            lists.add(shopUserData1);
            ShopUserData shopUserData2 = new ShopUserData("流水",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "迎春", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData2.setUserId("2");
            lists.add(shopUserData2);
            this.dataList.clear();
            this.dataList.addAll(MineNongyouActivity.shopUserData);
            this.dataList .addAll(lists);
            dataFollowList = dataList.stream().filter(ShopUserData::isFollow).collect(Collectors.toList());
            if (dataList.size() >= 3) {
                mPage += 1;
            }
            followFragment.setData(dataFollowList);
            newsFragment.setData(dataList);
        } else {
            List<ShopUserData> lists = new ArrayList<>();
            ShopUserData shopUserData3 = new ShopUserData("节日快乐",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "商秋菜篮子2", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData3.setUserId("3");
            lists.add(shopUserData3);
            ShopUserData shopUserData4 = new ShopUserData("节日快乐",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "商秋菜篮子3", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData4.setUserId("4");
            lists.add(shopUserData4);
            ShopUserData shopUserData5 = new ShopUserData("节日快乐",
                    "https://t7.baidu.com/it/u=1148322283,2872513312&fm=193&f=GIF",
                    "商秋菜篮子5", "2024-12-12", false, imageUrl, 123, 890
            );
            shopUserData5.setUserId("5");
            lists.add(shopUserData5);
            if (lists.size() >= 3) {
                mPage += 1;
            }
            List<ShopUserData> newAddFollowLists = lists.stream().filter(ShopUserData::isFollow).collect(Collectors.toList());
            followFragment.addData(newAddFollowLists);
            newsFragment.addData(lists);
            dataFollowList.addAll(newAddFollowLists);
            dataList.addAll(lists);

        }
    }

    private void showBottomPop(View view) {
        // 在Activity或Fragment中
        Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 无标题
        dialog.setContentView(R.layout.pop_window); // 设置布局文件
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp =dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(lp);
        dialog.setCancelable(true); // 点击外部是否取消对话框
        // 初始化布局中的控件
        ImageView imgDelete = dialog.findViewById(R.id.img_delete);

        imgDelete.setOnClickListener(v -> {
            // 取消按钮的点击事件
            dialog.dismiss();
        });

        dialog.show(); // 显示对话框
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mImageView = view.findViewById(R.id.mine_image);
        mPubNong = view.findViewById(R.id.publish_nong);
        mPubNong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), PublishNongJiActivity.class);
                intent.putExtra("page", Constance.PUBLISH_NONGYOU);
                startActivityForResult(intent,1);
//                showBottomPop(view);
            }
        });
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), MineNongyouActivity.class);
                startActivity(intent);
            }
        });
        mTextView = view.findViewById(R.id.mine_text);
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), MineNongyouActivity.class);
                startActivity(intent);
            }
        });
        viewPager2 = view.findViewById(R.id.myviepage2);
        viewPager2.setSaveEnabled(false);
        viewPager2.setUserInputEnabled(false);
        tabLayout = view.findViewById(R.id.mytablayout2);

        //看这里看这里看这里

        List<String> titleList = initPageTitleList();

        TabLayoutChildViewPager tabLayoutChildViewPager =
                new TabLayoutChildViewPager(getActivity(), initChildFragmentList());
        initDiscountList(mPage);
        //重点!! ViewPager2绑定Adapter
        viewPager2.setAdapter(tabLayoutChildViewPager);
        //重点!! 关联 TabLayout 和 ViewPager2
        new TabLayoutMediator(tabLayout, viewPager2, true,
                (tab, position) -> tab.setText(titleList.get(position)))
                .attach();
        tabLayout.getTabAt(0).setCustomView(R.layout.main_top_item);
        toMyTextView = tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tv_top_item);
        toMyTextView.setText(titleList.get(0));
        tabLayout.getTabAt(1).setCustomView(R.layout.main_top_item);
        toBeReceivedTextView = tabLayout.getTabAt(1).getCustomView().findViewById(R.id.tv_top_item);
        toBeReceivedTextView.setText(titleList.get(1));
        tabLayout.setTabRippleColor(ColorStateList.valueOf(getContext().getResources().getColor(R.color.trans)));/*去除tablayout 子tab点击时的黑色背景*/
//默认选择第一个tab,设置字体大小和默认风格为加粗 toMyTextView是我自己项目中第一个Tab的TextView,自己看着改。
        toMyTextView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        toMyTextView.setTextSize(COMPLEX_UNIT_SP, 22);
        toMyTextView.setTextColor(getActivity().getColor(R.color.black));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tab.getCustomView().findViewById(R.id.tv_top_item).setSelected(true);
                TextView tv = tab.getCustomView().findViewById(R.id.tv_top_item);
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);//直接用setTextSize(22)也一样
                tv.setTextColor(getActivity().getColor(R.color.black));
                tv.invalidate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.getCustomView().findViewById(R.id.tv_top_item).setSelected(false);
                TextView tv = tab.getCustomView().findViewById(R.id.tv_top_item);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));//加粗
                tv.setTextColor(getActivity().getColor(R.color.grey));
                tv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private List<String> initPageTitleList() {
        return Arrays.asList("关注", "最新");
    }

    FollowFragment followFragment, newsFragment;

    private List<Fragment> initChildFragmentList() {
        //在tablayout 的第一个fragment 中使用 RecycleView 优化一下页面
        followFragment = initFg(Constance.FOLLOW_PAGE);
        newsFragment = initFg(Constance.NEW_PAGE);
        return Arrays.asList(
                followFragment,
                newsFragment);
    }

    private FollowFragment initFg(String page) {
        FollowFragment fg = FollowFragment.newInstance(page, "");
        fg.setParentFg(this);
        return fg;
    }

    public void updateData(ShopUserData shopUserData, int position) {
        followFragment.updateData(shopUserData);
    }

    public void refreshData() {
        updateFragment();
    }

    public void addMoreData() {
        initDiscountList(mPage);
    }

    private void updateFragment() {
        mPage = 1;
        initDiscountList(mPage);
        followFragment.setData(dataFollowList);
        newsFragment.setData(dataList);
    }

    static class TabLayoutChildViewPager extends FragmentStateAdapter {

        private List<Fragment> fragmentList;

        public TabLayoutChildViewPager(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragmentList) {
            super(fragmentActivity);
            this.fragmentList = fragmentList;
        }


        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return fragmentList.size();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode ==1&& resultCode==1){
           ShopUserData shopUserData= (ShopUserData) data.getSerializableExtra("data");
            dataList.add(0,shopUserData);
            newsFragment.addData(shopUserData,0);
            MineNongyouActivity.shopUserData.add(shopUserData);
        }
    }
}